package com.clp.protocol.modbus_tcp.client.pipeline.check;

import com.clp.protocol.modbus_tcp.definition.ConstVal;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CheckMbFrmInHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(CheckMbFrmInHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf msgByteBuf = (ByteBuf) msg;
        if (msgByteBuf.readableBytes() == 0  // 没有信息内容
                || msgByteBuf.readableBytes() < ConstVal.MB_HEAD_LEN // 信息内容不足
        ) {
            LOGGER.info("报文无效，已丢弃！");
            msgByteBuf.release(); // 释放空间
            return;
        }
        ctx.fireChannelRead(msg);
    }
}
